

angular.module('imgApp').controller('HomeCtrl', ['$rootScope', '$scope', '$state', '$http', '$timeout', '$filter', '$window', 'localStorageService',
function($rootScope, $scope, $state, $http, $timeout, $filter, $window, localStorageService) {
	console.log("=============HomeCtrl=============");
	const MAX_SIZE = 3;
	$scope.matchImgShow = false;
	$scope.covers = new Map();
	$scope.covers.set("QD2", "QD2图(4)3104x3104.jpg");
	$scope.covers.set("QD3", "QD3A(43)2904x2835.jpg");
	$scope.covers.set("QD4", "QD4(9)4724x4724.jpg");
	$scope.covers.set("QD5", "QD5A(44)6299x6299.jpg");
	$scope.covers.set("QD6", "QD6A(1,2)1772x4724 .jpg");
	$scope.covers.set("QD7", "QD7A(3)12598x7874.jpg");
	$scope.covers.set("QD8", "QD8A(28)9071x5669.jpg");
	$scope.covers.set("QD9", "QD9B(74)2953x4134.jpg");
	$scope.coverNames = [];
	$scope.coverIndex = -1;
	$scope.query = [];
	$scope.collectionShow = true;
	$scope.tempImgShow = false;
	$scope.bgmText = '以图识图';
	$scope.searchOpts = [{
		name: "图库图片",
		mode: 0
	}, {
		name: "以图识图",
		mode: 1
	}];
	$scope.ph = ["请输入图库或图片关键字", "点击下面按钮上传图片"];
	for (var i = 0; i < $scope.searchOpts.length; i++) {
		$scope.query.push("");
	}
	$scope.curOpt = $scope.searchOpts[0];
	$scope.pos = 0;
	$scope.matchedImg = [];
	$scope.optChange = function() {
		$scope.pos = $scope.curOpt.mode;
		if ($scope.pos) {
			$scope.matchImgShow = true;
		} else {
			$scope.matchImgShow = false;
		}
	}
	$scope.isUpload = false;
	$scope.showFile = function() {
		$scope.isUpload = false;
		$scope.matchedImgs = [];
		var inputObj = document.getElementById('_ef');
		inputObj.click();
		inputObj.value;
		inputObj.onchange = function() {
			//console.log('---------showfile---------');
			var reader = new FileReader();
			reader.readAsDataURL(this.files[0]); // 调用readAsDataURL方法读取文件
			$scope.tempImg = this.files[0];
			var size = this.files[0].size;
			reader.onload = function() {
				var imgFile = reader.result;
				if (size <= MAX_SIZE * 1024 * 1024) {
					document.getElementById("temp-img").src = imgFile;
					$scope.isUpload = true;
					matchResults = [];
					$scope.matchImg();
				} else {
					alert('上传图片大小不得大于' + MAX_SIZE + 'MB!');
				}
			};
		}
	}
	
	var getCoverImgs = function(collections, coverMap) {
		var coverNames = [];
		if (collections) {
				for(var i = 0; i < collections.length; i++) {
				coverNames.push(coverMap.get(collections[i]));
			}
			return coverNames;
		}
		return [];
	}

	$scope.getCollections = function() {
		console.log("=====get collections=====");
		$http({
				method: 'GET',
				url: $rootScope.baseUrl + 'api/collections'
		}).then(function(res) {
				$scope.allCollections = res.data;

			}, function(err) {
			
			});
	}

	$scope.fitImgs = function(id, arr) {
		console.log("======fitImgs======");
		console.log(arr.length);
		var len = arr.length,
			padWidth = 200;
	    $timeout(function() {
	    	for(var i = 0; i < len; i++) {
			var img = document.getElementById(id + i);
			console.log(img)
			var w = img.naturalWidth,
				h = img.naturalHeight;
			console.log(w);
			console.log(h);
			autofit(img, w, h, padWidth);
			}
	    }, 1000);
		
	}
	$scope.$watch('query[0]', function(newVal, oldVal) {
		var re = $filter('filter')($scope.collections, $scope.query[$scope.pos]);
		$scope.coverNames = getCoverImgs(re, $scope.covers);
	});
	
	$scope.getCollections();
	
	/**
	 * login
	 */
	$scope.login = function() {
		$rootScope.qqLogin = false;
		if ($scope.username && $scope.password) {
			$http({
				method: 'POST',
				url: $rootScope.baseUrl + 'api/login',
				data: {
					username: $scope.username,
					password: $scope.password,
					qqLogin: $rootScope.qqLogin 
				}
			}).then(function(res) {
				localStorageService.set('curUser', res.data);
				localStorageService.remove('qqUser');
				$rootScope.user = res.data;
				if ($rootScope.user.role === 0) $rootScope.access = true;
				$rootScope.isLogin = true;
				$rootScope.normalUser = true;
				$('#loginModal').modal('hide');
				$('.modal-backdrop').hide();
				$rootScope.getUserCollections(true);

				if(!$rootScope.collectMode) {
					$scope.loginSucceed();
				}
			}, function(err) {
				alert(err.data);
			});
		} else {
			alert('用户名或密码不能为空！');
		}
	}
	
	$scope.loginSucceed = function() {
		$state.go('user');
	}
	
	$scope.toRegisterModal = function() {
		$("#registerModal").modal("show");
		$("#loginModal").modal("hide");
	}
	
	$scope.register = function(user, pwd) {
		user = user || $scope.regUser;
		pwd = pwd || $scope.regPwd;
		if (user && pwd) {
			$http({
				method: "POST",
				url: $rootScope.baseUrl + "api/register",
				data: {
					username: user,
					password: pwd
				}
			}).then(function(res) {
				alert('注册成功！');
				$("#registerModal").modal("hide");
				$scope.regUser = '';
				$scope.regPwd = '';
			}, function(err) {
				alert('注册失败！');
			});
		} else {
			alert("用户名和密码不能为空！");
		}
		
	}
	
	$scope.enterCollection = function(name, index) {
		name = name || $scope.allCollections[index].cname;
		$scope.collectionName = name;
		$scope.coverIndex = index;
		$http({
			method: "GET",
			url: $rootScope.baseUrl + "api/collections/" + name + "/images"
		}).then(function(res) {
			$scope.allImgs = res.data;
			$scope.collectionShow = false;
		}, function(err) {
			console.log(err.data);
		});
	}
	
	$scope.backToCollection = function() {
		$scope.matchImgShow = false;
		$scope.collectionShow = true;
		$scope.pos = 0;
		$scope.curOpt = $scope.searchOpts[$scope.pos];
		$scope.getCollections();
	}
	$scope.collectionImg = function($event, img) {
		$event.stopPropagation();
		$rootScope.collectMode = true;
		if (!$rootScope.isLogin) {
			$("#loginModal").modal("show");
		} else {
			console.log('collect-view');
			$("#collect-view").modal("show");		
			$scope.imgSrc = img;
			$('#s0').addClass('selected');
		}
	}
	
	$scope.collectSet = function($event) {
		$event.stopPropagation();
		$rootScope.collectMode = true;
		if (!$rootScope.isLogin) {
			$("#loginModal").modal("show");
		} else {
			console.log('collect-view');
			$("#img-view").modal("hide");
			$("#collect-view").modal("show");		
		}
	}
	
	
	/**
	 * Like function
	 * @param {Object} $event
	 */
	$scope.like = function($event) {
	 	$event.stopPropagation();
	 	var status = $($event.target).hasClass("unlike");
      	if (status) {  
      		$($event.target).removeClass("unlike");  
        	$($event.target).addClass("like");  
      	} else {  
        	$($event.target).removeClass("like");  
        	$($event.target).addClass("unlike"); 
      	}  
	}
	
	/**
	 * Open image
	 * @param {Object} img
	 */
	$scope.openImg = function(img, mode) {
		mode = mode || 0;
		if (mode) {
			$scope.collectionName = $scope.cname;
		}
		if (img.indexOf(".jpg") < 0) img += ".jpg";
		$scope.imgSrc = img;
		var pic = document.getElementById("img-open");
		pic.onload = function() {
			var w = pic.naturalWidth,
				h = pic.naturalHeight,
				ratio = w / h;
			autofit(pic, w, h, d);
		}
		$("#img-view").modal("show");
	}
	/**
	 * Toggle image
	 * @param {Object} img
	 */
	$scope.toggleImg = function(img) {
		$scope.imgSrc = img;
	}
	/**
	 * Logout
	 */
	$rootScope.logOut = function() {
		$state.go('home');
		if (QC.Login.check()) {
			QC.Login.signOut();
			
			if (!QC.Login.check()) {
				console.log("已经登出!");
			}
		}
		$rootScope.isLogin = false;
		$rootScope.normalUser = false;
		$rootScope.qqLogin = false;
		$rootScope.user = {};
		$rootScope.qqUser = {};
		$rootScope.access = false;
	}
	
	$('.user-area-nav').hover(function() {
		$('.user-options').removeClass('ng-hide');
	});
	
	$('.user-options').mouseout(function() {
		$timeout(function() {
			$('.user-options').addClass('ng-hide');
		}, 1000);
	});
	$('.user-options').hover(function() {
		$('.user-options').removeClass('ng-hide');
	});
	
	$scope.recordSet = function(cname) {
		var set = cname;
		$http({
			method: "POST",
			url: $rootScope.baseUrl + 'api/recordset',
			data: {
				set:set
			}
		}).then(function(res) {
			alert(res.data);
		}, function(err) {
			alert(err.data);
		});
	}
	$scope.compress = function(cname) {
		cname = cname || $scope.set;
		$http({
			method: "GET",
			url: $rootScope.baseUrl + 'api/compress/' + cname
		}).then(function(res) {
			alert(res.data);
		}, function(err) {
			alert(err.data);
		});
	}
	
	var regex = new RegExp(/QD[0-9]+/g);
	var allImgsMap = new Map();

	$scope.matchImg = function(imgSrc, reg) {
		$scope.bgmText = '以图识图';
		imgSrc = imgSrc || document.getElementById("temp-img").src;
		console.log("-------识图中----------");
		matchResults = [];
		if ($scope.curOpt.mode) {
			if ($scope.tempImg) {
				var data = new FormData(document.getElementById('add-bgi'));
				$http({
					method: 'POST',
					url: $rootScope.baseUrl + 'api/search',
					headers: {
						'Content-Type': undefined
					},
					data: data
				}).then(function(res) {
				    var r = res.data;
				    var temp = [];
				    $scope.matchedImgs = [];
				    Object.keys(r).forEach(k => {
				    	var arr = r[k];
				   		for (var i = 0; i < arr.length; i++) {
				   			arr[i].imgname = arr[i].img;
				   			arr[i].img = k + "/" + arr[i].img;
				   			temp.push(arr[i]);
				   		}
				    });
				    quick(temp, 0, temp.length - 1);
				    for (var i = 0; i < temp.length; i++) {
				    	$scope.matchedImgs.push({
				    		imgurl: temp[i].img,
				    		name: temp[i].imgname
				    	});
				    }
				    console.log($scope.matchedImgs);
				    if ($scope.matchedImgs.length == 0) {
				    	$scope.bgmText = '没有相似图片！';
				    }
				}, function(err) {
					alert(err.data);
				});
			} else {
				alert("请上传图片");
			}
			
		} else {
			alert("输入关键字后会自动显示搜索结果！");
		}
		
	}

	
	function cbLogin(reqData, opts) {
		console.log("login success!");
		$scope.$applyAsync(function() {
			$rootScope.isLogin = true;
			$rootScope.normalUser = false;
			$rootScope.qqUser = reqData;
			$rootScope.qqLogin = true;
			$http({
				method: 'POST',
				url: $rootScope.baseUrl + 'api/login',
				data: {
					username: $rootScope.qqUser.nickname,
					password: "qqlogin",
					qqLogin: $rootScope.qqLogin
				}
			}).then(function(res) {
				console.log(res.data);
				$rootScope.user = res.data;
				if ($rootScope.user.role === 0) $rootScope.access = true;
				localStorageService.set('curUser', res.data);
				localStorageService.set('qqUser', $rootScope.qqUser);
				$('#loginModal').modal('hide');
				if(res.data.hasOwnProperty("id")) $rootScope.getUserCollections(true);
	
			}, function(err) {
	
			});
		});
		$('#loginModal').modal('hide');
	}
	
	function cbLogoutFun(){
    	alert("注销成功!");
    	$rootScope.isLogin = false;
		$rootScope.normalUser = true;
	};

	QC.Login({
			btnId: "qqLoginBtn"
		}, cbLogin, cbLogoutFun);

}]);
